package com.rex.editor.common;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Base64;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Utils {

    private Utils() throws InstantiationException {
        throw new InstantiationException("This class is not for instantiation");
    }


    /**
     * 获取 html 中的纯文本
     */
    public static String getHtml2Text(String inputString) {
        //处理空格和换行符
        inputString = inputString.replaceAll("\n", "");

        inputString = inputString.replaceAll("&nbsp;", " ");
        inputString = inputString.replaceAll("<br>", "\n");

        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_script;
        Matcher m_script;
        Pattern p_style;
        Matcher m_style;
        Pattern p_html;
        Matcher m_html;
        Pattern p_html1;
        Matcher m_html1;

        try {
            String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>
            String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            String regEx_html1 = "<[^>]+";
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
            m_html1 = p_html1.matcher(htmlStr);
            htmlStr = m_html1.replaceAll(""); // 过滤html标签

            textStr = htmlStr;

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        textStr = textStr.replaceAll("&gt;", "");
        return textStr;// 返回文本字符串
    }

    /**
     * 移除段落标签
     */
    public static String removeP(String html) {
        String result = html;
        if (result.contains("<p>") && result.contains("</p>")) {
            result = result.replace("<p>", "");
            result = result.replace("</p>", "<br>");
            while (result.endsWith("<br>")) {
                result = result.substring(0, result.length() - 4);
            }
        }
        return result;
    }

    public static List<String> getImageUrl(String html) {
        ArrayList<String> listData = new ArrayList<>();
        if (TextUtils.isEmpty(html)) {
            return listData;
        }
        Document doc = Jsoup.parse(html);

        Elements elementsImg = doc.select("img[src]");
        Elements elementsVideo = doc.select("video[src]");

        Elements elementsSrc = new Elements();
        elementsSrc.addAll(elementsImg);
        elementsSrc.addAll(elementsVideo);

        for (Element element : elementsSrc) {
            String src = element.attr("src");
            if (!TextUtils.isEmpty(src)) {
                listData.add(src);
            }
        }
        return listData;
    }


    public static String getBodyContent(String html) {
        if (TextUtils.isEmpty(html)) {
            return "";
        }
        Document doc = Jsoup.parse(html);
        Elements elementsP = doc.select("body");
        String sstr = "";
        for (Element element : elementsP) {
            List<Node> list = element.childNodes();
            if (list != null) {
                for (Node node : list) {
                    sstr += node.toString();
                }
            }

        }
        return sstr;
    }

    /**
     * 根据name属性  也就是类型获取包括标签在内的内容
     *
     * @param html
     * @param name
     * @return
     */
    public static List<String> getContextForName(String html, String name) {
        if (TextUtils.isEmpty(html)) {
            return null;
        }
        Document doc = Jsoup.parse(html);
        List<String> listData = new ArrayList();
        Elements elementsImg = doc.select("label[name]");
        Elements elementsP = doc.select("p[name]");

        Elements elementsSrc = new Elements();
        elementsSrc.addAll(elementsImg);
        elementsSrc.addAll(elementsP);

        for (Element element : elementsSrc) {
            String names = element.attr("name");
            String data = element.attr("data");
            String va = element.text();

            if (names.equals(name)) {
                listData.add(data + "," + va);
            }
        }

        return listData;
    }

    //获取label  data属性的值
    public static Map<String, String> getLabelDataValue(String html) {
        if (TextUtils.isEmpty(html)) {
            return null;
        }

        Map<String, String> map = new HashMap<>();

        Document doc = Jsoup.parse(html);

        Elements elementsImg = doc.select("label[name]");
        Elements elementsP = doc.select("p[name]");

        Elements elementsSrc = new Elements();
        elementsSrc.addAll(elementsImg);
        elementsSrc.addAll(elementsP);

        for (Element element : elementsSrc) {
            String name = element.attr("name");
            String data = element.attr("data");
            String datas = map.get(name);
            if (datas == null) {
                map.put(name, data);
            } else map.put(name, datas + "," + data);

        }

        return map;
    }


    /**
     * 获取html本地的地址 方便上传的时候转为在线的地址
     *
     * @param html
     * @return
     */
    public static List<String> getHtmlSrcOrHrefList(String html) {

        if (TextUtils.isEmpty(html)) {
            return null;
        }
        Document doc = Jsoup.parse(html);
        List<String> listData = new ArrayList();

        Elements elementsSrc = new Elements();
        Elements elementsImg = doc.select("img[src]");
        Elements elementsAudio = doc.select("audio[src]");
        Elements elementsVideo = doc.select("video[src]");
        elementsSrc.addAll(elementsImg);
        elementsSrc.addAll(elementsAudio);
        elementsSrc.addAll(elementsVideo);

        Elements elementsFiles = doc.select("a[href]");
        Elements elementsPosters = doc.select("video[poster]");


        for (Element element : elementsSrc) {
            String src = element.attr("src");
            if (!TextUtils.isEmpty(src) && !src.contains("http")) {
                listData.add(src);
            }
        }

        for (Element element : elementsFiles) {
            String src = element.attr("href");
            if (!TextUtils.isEmpty(src) && !src.contains("http")) {
                listData.add(src);
            }
        }
        for (Element element : elementsPosters) {
            String src = element.attr("poster");
            if (!TextUtils.isEmpty(src) && !src.contains("http")) {
                listData.add(src);
            }
        }

        return listData;
    }

    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    public static Bitmap decodeResource(Context context, int resId) {
        return BitmapFactory.decodeResource(context.getResources(), resId);
    }

    public static long getCurrentTime() {
        return System.currentTimeMillis();
    }

    /**
     * 获取视频缩略图
     *
     * @param filePath
     * @return
     */
    public Bitmap getVideoThumbnail(String filePath) {
        Bitmap b = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            b = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();

        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return b;
    }


    public static byte[] toBase64byte(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public static String toBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

}
